package com.mms.service.impl;

import com.mms.mapper.SysMenuMapper;
import com.mms.model.pojo.SysMenu;
import com.mms.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @auth wzy
 * @date 2023/11/21 11:42
 */
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> treeList() {
        //获取所有菜单记录
        List<SysMenu> menuList = sysMenuMapper.list();

        //组织成Tree
        // 获取顶层菜单
        List<SysMenu> topMenuList = menuList.stream()
                .filter(menu -> menu.getParentId() == 0)
                .collect(Collectors.toList());

        for (SysMenu parentMenu : topMenuList) {
            setChildrenMenus(parentMenu,menuList);
        }

        return topMenuList;
    }

    /**
     * 给父菜单设置子菜单
     * @param parentMenu
     * @param menuList
     */
    private void setChildrenMenus(SysMenu parentMenu,List<SysMenu> menuList) {

        List<SysMenu> childrenMenuList = menuList.stream()
                .filter(menu -> menu.getParentId() == parentMenu.getMenuId())
                .collect(Collectors.toList());

        parentMenu.setChildren(childrenMenuList);

        for (SysMenu menu : childrenMenuList) {
            setChildrenMenus(menu,menuList);
        }

    }
}
